package com.cpg.school.controller.service;

import com.cpg.school.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@RestController
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login_in.do")
    public void login_in(HttpServletResponse response, HttpSession session, String userName, String password) throws IOException {
        Map login = userMapper.login(userName, password);
        if (login == null) {
            response.sendRedirect("/login.do?fail=fail");
        } else {
            session.setAttribute("user_id", login.get("id").toString());
            session.setAttribute("login_name", login.get("login_name"));
            session.setAttribute("user_type", login.get("user_type").toString());
            response.sendRedirect("/index.do");
        }
    }

    @GetMapping("/login_out.do")
    public void login_out(HttpServletResponse response, HttpSession session) throws IOException {
        session.removeAttribute("user_id");
        session.removeAttribute("login_name");
        session.removeAttribute("user_type");
        response.sendRedirect("/login.do");
    }
}
